<template>
	<view>
		<s-pull-scroll class="" :down-offset="120" showDownSuccess="true" ref="pullScroll" :pullDown="pullDown"
			custom-style="'background-color: black;'">
			<view class="wrap">
				<view class="u-tabs-box">
					<u-tabs-swiper activeColor="#004fbf" ref="tabs" :list="list" :current="current" @change="change"
						:is-scroll="false" swiperWidth="750"></u-tabs-swiper>
				</view>

				<swiper class="swiper-box" :current="swiperCurrent" @transition="transition"
					@animationfinish="animationfinish">
					<swiper-item class="swiper-item">
						<scroll-view scroll-y style="height: 100%; width: 100%" @scrolltolower="reachBottom">
							<view class="page-box">
								<!--		预约卡片 START		-->
								<order-card :order="{ ...order, orderIndex: index }" :tag-name="'租'"
									v-for="(order, index) in orderList" :key="order.id" @toDeleteOrder="
                    delList(order,index)
                  " @toRecover="recoverAppointment(order)" @toCancel="cancelAppointment(order)"
									@toConfirmCancel="confirmOrderOperation(order, 2)"
									@toConfirmAppointment="confirmOrderOperation(order, 3)"
									@confirmComplete="confirmOrderOperation(order, 5)"></order-card>
								<!--		预约卡片 END					-->
							</view>
							<uni-load-more v-show="showLoading" class="loadMore" :status="status" :icon-size="12"
								:content-text="contentText" />
						</scroll-view>
					</swiper-item>

					<swiper-item class="swiper-item">
						<scroll-view style="height: 100%; width: 100%" scroll-y @scrolltolower="reachBottom">
							<view class="page-box">
								<!--		预约卡片 START					-->
								<order-card :order="{ ...order, orderIndex: index }" :tag-name="'售'"
									v-for="(order, index) in orderList2" @toDeleteOrder="
                    delList(order,index)
                  " :key="order.id" @toCancel="cancelAppointment(order)" @toRecover="recoverAppointment(order)"
									@toConfirmCancel="confirmOrderOperation(order, 2)"
									@toConfirmAppointment="confirmOrderOperation(order, 3)"
									@confirmComplete="confirmOrderOperation(order, 5)"></order-card>
								<!--		预约卡片 END					-->
							</view>
							<uni-load-more v-show="showLoading" class="loadMore" :status="status2" :icon-size="12"
								:content-text="contentText2" />
						</scroll-view>
					</swiper-item>
				</swiper>
			</view>
		</s-pull-scroll>
	</view>
</template>

<script>
	import {
		filter
	} from '@/util/reuse/filter';
	import {
		loadMore
	} from '../../util/reuse/loadMore';
	import {
		tokenRequest
	} from '../../util/network';
	import sHouseCard from '../../components/sHouseCard';
	import {
		d_uniShowToast,
		TOAST_DURATION,
		uniShowToast
	} from '../../util/misc';
	import {
		resetComponentData,
		uniMakePhoneCall
	} from '../../util/funcs';
	import houseMan from '../displayDetails/houseMan';
	import orderCard from './orderCard';
	import {
		pullDownRefresh
	} from '../../util/reuse';
	import {
		USER_ORIENTED
	} from '../../util/config';
	import {
		TESTING
	} from '@/util/test';
	let swiperCurrent = TESTING ? 1 : 0;

	function calculateOrderStatus(num) {
		let res = '';
		// let t = num % 5
		switch (num) {
			case 0:
				res = '待预约';
				break;
			case 1:
				res = '取消中';
				break;
			case 2:
				res = '已取消';
				break;
			case 3:
				res = '已预约';
				break;
			case 4:
				res = '恢复中';
				break;
			case 5:
				res = '已完成';
				break;
			case 6:
				res = '已失效';
				break;
			default:
				res = 'err: ' + num;
		}
		return res;
	}

	function afterFailForOrder(order, data) {
		if (!data.data) {
			console.warn('data err:', data);
			return;
		}
		d_uniShowToast({
			title: data.msg + ', 订单数据刷新',
		});

		this.$set(order, 'status', calculateOrderStatus(data.data.status));
	}
	// dateStr 2020-11-12
	function formatDate(dateStr) {
		let tArr = dateStr.split('-');
		return tArr[1] + '月' + tArr[2] + '日';
	}

	export default {
		mixins: [filter, loadMore, pullDownRefresh],
		components: {
			sHouseCard,
			houseMan,
			orderCard,
		},
		data() {
			return {
				// 不发请求, 前端测试用
				mockRequest: false && TESTING,
				USER_ORIENTED: USER_ORIENTED,
				orderStatus: '',
				list: [{
						name: '租',
					},
					{
						name: '售',
					},
				],
				orderList: [], // 租
				orderList2: [], // 售
				current: swiperCurrent,
				swiperCurrent: swiperCurrent,
				tabsHeight: 0,
				dx: 0,
				loadStatus: ['loadmore', 'loadmore', 'loadmore', 'loadmore'],
				date: '', // 日期
				visitTime: '', // 预约时间
			};
		},
		mounted() {
			this.initPageData();
		},
		computed: {
			// 价格小数
			priceDecimal() {
				return (val) => {
					if (val !== parseInt(val)) return val.slice(-2);
					else return '00';
				};
			},
			// 价格整数
			priceInt() {
				return (val) => {};
			},
		},
		methods: {
			delList(order, index) {
				this.updateList({
					...order,
					orderIndex: index
				}, this.orderList)
			},
			updateList(order, list) {
				if (this.mockRequest) {
					list.splice(order.orderIndex, 1);
					uniShowToast('删除成功', false);
					return;
				}
				tokenRequest(
					'/del_appointment_list', {
						appointment_id: order.id
					}, {
						success: ({
							data
						}) => {
							if (data.code === 200) {
								list.splice(order.orderIndex, 1);
								uniShowToast(data.msg);
							} else {
								uniShowToast(data.msg, false);
							}
						},
					}
				);
				// console.log(111);
				// console.log(e);
			},
			async initPageData() {
				let t = this.current;
				resetComponentData.call(this, () => {
					this.current = this.swiperCurrent = t;
				});

				await Promise.all([this.getListData(1), this.getListData(2)]);
			},
			makePhoneCall(num) {
				uniMakePhoneCall(num);
			},
			washData(arr) {
				for (let orderItem of arr) {
					orderItem.status = calculateOrderStatus(orderItem.status) || 'errWash';

					let tArr = orderItem.visit_time.split(' ');
					this.$set(orderItem, 'visitDate', formatDate(tArr[0]));
					// console.log(tArr[1])
					this.$set(orderItem, 'visitTime', tArr[1]);
				}
			},
			/**
			 * @param order
			 * @param operation 0 确认恢复,  2 取消预约 , 3 接受预约
			 */
			confirmOrderOperation(order, operation) {
				let postData = {
					id: order.id,
					status: operation,
				};
				// console.log(postData);
				// return;
				tokenRequest('/appointment_operation', postData, {
					success: ({
						data
					}) => {
						if (data.code === 200) {
							console.log(data);
							d_uniShowToast({
								title: data.msg,
							});

							this.$set(order, 'status', calculateOrderStatus(operation));
						} else {
							this.$set(order, 'status', calculateOrderStatus(data.data.status));

							d_uniShowToast({
								title: data.msg + ', 订单数据刷新',
							});
						}
					},
				});
			},
			cancelAppointment(order) {
				if (order.status === '已取消' || order.status === '取消中') {
					return;
				}
				uni.showModal({
					content: '是否取消预约',
					success: (res) => {
						if (res.confirm) {
							tokenRequest(
								'/cancel_appointment', {
									id: order.id,
								}, {
									success: ({
										data
									}) => {
										if (data.code === 200) {
											this.$set(order, 'status', '取消中');
											d_uniShowToast({
												title: data.msg,
												duration: TOAST_DURATION,
											});
										} else {
											afterFailForOrder.call(this, order, data);
										}
									},
								}
							);
						}
					},
				});
			},
			recoverAppointment(order) {
				if (!USER_ORIENTED) {
					// 招商端跑另一个逻辑
					this.confirmOrderOperation(order, 0);
					return;
				}
				// 以下均为用户端逻辑
				if (order.status === '待预约' || order.status === '预约中') {
					return;
				}

				tokenRequest(
					'/restore_appointment', {
						id: order.id,
					}, {
						success: ({
							data
						}) => {
							if (data.code === 200) {
								this.$set(order, 'status', '恢复中');
								d_uniShowToast({
									title: data.msg,
									duration: TOAST_DURATION,
								});
							} else {
								afterFailForOrder.call(this, order, data);
							}
						},
					}
				);
			},
			reachBottom() {
				let type = this.swiperCurrent + 1;
				if (type === 1) {
					this.pagi.page += 1;
				} else {
					this.pagi2.page += 1;
				}
				this.getListData(type);
			},
			getListData(type) {
				// return new Promise(resolve => {
				// console.log(type)
				if (type === 1) {
					if (this.status === 'nomore') return;
					this.status = 'loading';
					return new Promise((resolve) => {
						let postData = {
							type: type,
							...this.pagi,
						}
						this.$tokenRequest('/appointment_list', postData).then((data) => {
							console.log('list1 ', data);
							let list = data.data;
							if (list.length < this.pagi.pageSize) {
								this.status = 'nomore';
							} else {
								this.status = 'more';
							}
							this.washData(list);
							// console.log(list)
							this.orderList = this.orderList.concat(list);
							// console.log('orderList: ',this.orderList[1]);
							resolve();
						}).catch((error) => {
							this.$refs.pullScroll.finish();
							this.status = 'nomore';
							console.log("appointment_list error", error);
						})
					});
				} else if (type === 2) {
					if (this.status2 === 'nomore') return;
					this.status2 = 'loading';
					return new Promise((resolve) => {
						let postData = {
							type: type,
							...this.pagi2,
						}
						this.$tokenRequest('/appointment_list', postData).then((data) => {
							let list = data.data;
							if (list.length < this.pagi2.pageSize) {
								this.status2 = 'nomore';
							} else {
								this.status2 = 'more';
							}
							this.washData(list);
							// console.log('list: ', list);
							this.orderList2 = this.orderList2.concat(list);
							resolve();
						}).catch((error) => {
							this.$refs.pullScroll.finish();
							this.status2 = 'nomore';
							console.log("appointment_list error", error);
						})
					});
				}
				return Promise.resove();
				// })
			},
			// tab栏切换
			change(index) {
				this.swiperCurrent = index;
			},
			transition({
				detail: {
					dx
				}
			}) {
				this.$refs.tabs.setDx(dx);
			},
			animationfinish({
				detail: {
					current
				}
			}) {
				this.$refs.tabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '../../assets/styles/global';

	.centre {
		text-align: center;
		margin: 200rpx auto;
		font-size: 32rpx;

		image {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
			margin-bottom: 20rpx;
		}

		.tips {
			font-size: 24rpx;
			color: #999999;
			margin-top: 20rpx;
		}

		.btn {
			margin: 80rpx auto;
			width: 200rpx;
			border-radius: 32rpx;
			line-height: 64rpx;
			color: #ffffff;
			font-size: 26rpx;
			background: linear-gradient(270deg,
					rgba(249, 116, 90, 1) 0%,
					rgba(255, 158, 1, 1) 100%);
		}
	}

	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top));
		width: 100%;
	}

	.swiper-box {
		flex: 1;
		background-color: #f7f8fa;
	}

	.swiper-item {
		height: 100%;
	}
</style>
